package com.wxtech.heartbeat.server.protocol;

import java.util.ArrayList;
import java.util.List;

import com.wxtech.heartbeat.util.CHexConver;

import io.netty.buffer.ByteBuf;

public class ProtocolHelper {
	private static List<String> supportProtocol;
	
	static {
		supportProtocol = new ArrayList<String>();
		supportProtocol.add(HeartBeatProtocolConstant.HEART_BEAT_CMD_HEX);
		supportProtocol.add(DataCollectProtocolConstant.DATA_COLL_CMD_HEX);
	}

	public ProtocolHelper() {
		// TODO Auto-generated constructor stub
	}
	
	public static String getCmdType(ByteBuf buffer) {
		//先尝试读取4个byte，heartbeat的byte是02 01 00 01
		byte[] cmdType = new byte[1];
		int beginIndex = buffer.readerIndex();
		buffer.getBytes(beginIndex, cmdType);
		String cmdTypeString = CHexConver.byte2HexStr(cmdType, 1);
		if(cmdTypeString.equals("02")) {
			return HeartBeatProtocolConstant.HEART_BEAT_CMD_HEX;
		}
		//第一个byte是01，就是data collect
		if(cmdTypeString.startsWith("01")) {
			return DataCollectProtocolConstant.DATA_COLL_CMD_HEX;
		}
		//其他都是无效的
		return Protocol.INVALID_CMD_HEX;
	}
	
	public static boolean isValidCmd(String hex) {
		if(supportProtocol.contains(hex)) {
			return true;
		}
		return false;
	}
	
	public static Protocol getProtocolByCmdHex(String hex) {
		if (HeartBeatProtocolConstant.HEART_BEAT_CMD_HEX.equals(hex)) {
			return new HeartBeatProtocolDecoder();
		}
		if (DataCollectProtocolConstant.DATA_COLL_CMD_HEX.equals(hex)) {
			return new DataCollectProtocolDecoder();
		}
		//看了没有先判断一下cmd是否有效，或者代码错误。
		return null;
	}

}
